package com.jk.controller;

import com.jk.po.ClentPO;
import com.jk.service.ClientLoginService;
import com.jk.utils.HttpClientUtil02;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/***
 * @ClassName: PhoneCodeController
 * @Description:TODO   短信验证码接口
 * @Auther: TaiBai
 * @Date: 2021/7/5 16:53
 * @version : V1.0
 */
@Api(tags = "短信验证码接口")
@RestController
@RequestMapping("code")
public class PhoneCodeController {
    @Autowired
    private ClientLoginService clientLoginService;
    @Autowired
    private RedisTemplate redisTemplate;
    /*
    * @Author  TaiBai
    * @Description //TODO 发送短信验证码接口
    * @Date 19:00 2021/7/5
    * @method  getCode
    * @Param [cusphone, session]
    * @return java.util.Map<java.lang.String,java.lang.Object>
    **/
    @ApiOperation(value = "短信验证码接口", notes = "返回验证码",produces ="cusphone")
    @PostMapping("getCode/{cusphone}")
    public @ResponseBody Map<String, Object> getCode(@PathVariable("cusphone")@ApiParam("手机号")String cusphone, HttpSession session) throws Exception {
        HashMap<String, Object> resultMap = new HashMap<>();
        Integer aa = 0;
        //  判断是否填写手机号码
        if (cusphone == null || cusphone == ""){
            //未填写手机号码，返回失败提示
            resultMap.put("message","请填写手机号");
            resultMap.put("status",0);
            return resultMap;
        }
        //  判断用户填写的手机号码是否合法
        if (!cusphone.matches("^1(([358]\\d)|66|76|77|99)\\d{8}$")){
            //手机号码不合法，返回失败提示
            resultMap.put("message","手机号不合法");
            resultMap.put("status",0);
            return resultMap;
        }
        //查看数据库是否有该手机号
        ClentPO resultClent = clientLoginService.queryClientByPhone(cusphone);
        if (resultClent == null || resultClent.equals("")){
            resultMap.put("message","该手机号未注册!");
            return resultMap;
        }
        //调用短信验证码工具类
        String sendCode = HttpClientUtil02.sendCode(cusphone);
        //json字符串转成json对象
        String code = sendCode.substring(31,37);

        //  判断获取短信验证码是否出现异常
        if (code.length() != 6) {
            //  说明返回的不是验证码，而是异常信息
            resultMap.put("message","验证码不正确!");
            resultMap.put("status",0);
            return resultMap;
        }
        //  将短信验证码保存到 Redis 中，有效期为5分钟
        //  key  ： 手机号码
        //  value： 验证码

       // String code = "123456";

        String Key = cusphone;						//设置过期时间
        redisTemplate.opsForValue().set(Key,code,5, TimeUnit.MINUTES);


        //发送成功返回
        resultMap.put("message","发送成功,请查收.验证码5分钟内有效");
        resultMap.put("status",1);
        return resultMap;
        }

}
